<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const microAppUrl = ref('http://localhost:3002/')
const microAppKey = ref(0) // 用于强制重新渲染
const isLoading = ref(false) // 加载状态
const dataKey = ref(0) // 用于强制触发数据更新

// 使用固定的微应用名称，避免动态名称导致的卸载问题
const microAppName = 'child-app-b'

// 构建子应用URL
const buildMicroAppUrl = (): string => {
  // 始终返回基础URL，避免 URL 构造错误
  return 'http://localhost:3002/'
}

// 监听路由变化，更新子应用URL
watch(
  () => route.path,
  async (newPath) => {
    console.log('主应用路由变化:', newPath)
    console.log('路由元信息:', route.meta)

    // 从路由元信息中获取子应用路由
    const childRoute = (route.meta?.childRoute as string) || '/'
    const newUrl = buildMicroAppUrl()

    console.log('子应用路由:', childRoute)
    console.log('子应用URL:', newUrl)

    // 更新微应用URL（如果有变化）
    if (microAppUrl.value !== newUrl) {
      console.log('子应用URL发生变化，重新加载子应用')
      isLoading.value = true
      microAppUrl.value = newUrl
      microAppKey.value++ // URL变化时重新加载整个微应用

      // 等待DOM更新
      await nextTick()

      setTimeout(() => {
        isLoading.value = false
      }, 500)
    } else {
      console.log('相同子应用内的路由切换，触发数据更新')
      // 相同子应用内的路由切换，通过递增dataKey确保数据传递
      dataKey.value++
      console.log('数据更新key:', dataKey.value)
    }
  },
  { immediate: true },
)

onMounted(() => {
  console.log('ChildB 容器页面已加载，当前路由:', route.path)
  console.log('子应用URL:', microAppUrl.value)
})
</script>

<template>
  <div class="child-app-container">
    <div class="child-app-header">
      <h2>子应用 B</h2>
      <p>当前路由: {{ route.path }}</p>
      <p>子应用URL: {{ microAppUrl }}</p>
      <p>路由元信息: {{ JSON.stringify(route.meta) }}</p>
    </div>
    <div class="child-app-content">
      <micro-app
        :key="microAppKey"
        :name="microAppName"
        :url="microAppUrl"
        :data="{ childRoute: route.meta?.childRoute || '/', from: 'main-app', dataKey: dataKey }"
        iframe
        disable-memory-router
        disable-patch-request
        @mounted="() => console.log('子应用 B 加载完成')"
        @unmount="() => console.log('子应用 B 卸载完成')"
        @error="(e: unknown) => console.error('子应用 B 出现错误:', e)"
      ></micro-app>
    </div>
  </div>
</template>

<style scoped>
.child-app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.child-app-header {
  background-color: #f5f5f5;
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.child-app-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.child-app-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.child-app-content {
  flex: 1;
  position: relative;
}

.child-app-content micro-app {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
